package cn.itcast.web.controller.cargo;


import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/export")
@Slf4j

public class ExportController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    /**
     * 1. 合同管理列表
     */
    @RequestMapping("/contractList")
    public String contractList(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer pageSize){
        log.info("查询开始");

        ContractExample contractExample = new ContractExample();
        // 根据create_time降序排序
        contractExample.setOrderByClause("create_time desc");
        ContractExample.Criteria criteria = contractExample.createCriteria();
        //查询本公司id的合同
        criteria.andCompanyIdEqualTo(getLoginCompanyId());

        //查询条件为购销合同状态为1（已上报）
        criteria.andStateEqualTo(1);
        PageInfo<Contract> pageInfo = contractService.findByPage(contractExample, pageNum, pageSize);

        //保存
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/export/export-contractList";
    }

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize){
        ExportExample exportExample = new ExportExample();
        //创建时间降序排列
        exportExample.setOrderByClause("create_time desc");
        ExportExample.Criteria criteria = exportExample.createCriteria();
        //查看本公司出口报运单
        criteria.andCompanyIdEqualTo(getLoginCompanyId());

        //分页
        PageInfo<Export> pageInfo = exportService.findByPage(exportExample, pageNum, pageSize);
        //保存
        request.setAttribute("pageInfo",pageInfo);

        return "cargo/export/export-list";
    }


    @RequestMapping("/toExport")
    public String toExport(String id){
        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }

    @RequestMapping("/edit")
    public String edit(Export export){
        export.setCompanyId(getLoginCompanyId());
        export.setCompanyName(getLoginCompanyName());
        //根据id判断是添加还是修改
        if(StringUtils.isEmpty(export.getId())){
            //因为列表排序按照创建时间降序，所以设置创建时间
            export.setCreateTime(new Date());
           exportService.save(export);
        }else {
            exportService.update(export);
        }
        return "redirect:/cargo/export/list";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(String id){
        //1. 根据id 查询报运单
        Export export = exportService.findById(id);
        //2.在商品表中根据报运单id查找商品
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> exportProducts = exportProductService.findAll(exportProductExample);

        //3.保存
        request.setAttribute("export",export);
        request.setAttribute("eps",exportProducts);
        return "cargo/export/export-update";
    }


    /**
     * 报运单状态的修改：提交、取消
     * @param id
     * @return
     */
    @RequestMapping("/submit")
    public String submit(String id) {
        // 提交：报运单状态为1
        Export export = new Export();
        export.setId(id);   // 修改条件
        //更新的sql语句条件where id = #{id}，所以需要传入id，并且这是新建的export对象，所以也有必要设置id
        export.setState(1); // 修改的值
        exportService.update(export);
        return "redirect:/cargo/export/list";
    }

    @RequestMapping("/cancel")
    public String cancel(String id) {
        // 提交：修改报运单状态为0
        Export export = new Export();
        export.setId(id);   // 修改条件
        export.setState(0); // 修改的值
        exportService.update(export);
        return "redirect:/cargo/export/list";
    }



    /**
     * 电子报运实现
     */
    @RequestMapping("/exportE")
    public String exportE(String id){
        //封装export对象
        ExportVo exportVo = new ExportVo();
        //根据id查找报运单
        Export export = exportService.findById(id);
        //数据搬家
        BeanUtils.copyProperties(export,exportVo);
        //【设置报运单的id到vo对象中】
        exportVo.setExportId(id);

        //封装exportProductVo对象，

        //所有商品的对象
        List<ExportProductVo> products = exportVo.getProducts();
        // 根据报运单id查询商品
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(exportProductExample);

        if(list!=null && list.size()>0){
            for (ExportProduct exportProduct : list) {
              //单个商品的对象
                ExportProductVo exportProductVo = new ExportProductVo();
                BeanUtils.copyProperties(exportProduct,exportProductVo);
                // 【设置报运单、商品id】
                exportProductVo.setExportProductId(exportProduct.getId());
                exportProductVo.setExportId(id);

                //再将每一个商品放到商品集合中
                products.add(exportProductVo);
            }
        }

        //1. 电子报运（1）远程访问海关报运平台录入报运单、商品信息
        WebClient.create("http://127.0.0.1:9001/ws/export/user").post(exportVo);

        //2. 电子报运（2）根据报运单id，查询报运结果
        ExportResult exportResult =
                WebClient.create("http://127.0.0.1:9001/ws/export/user/" + id).get(ExportResult.class);

        //从海关获取报运结果以后，就修改报运单
        exportService.updateExport(exportResult);
        return "redirect:/cargo/export/list";
    }



}
